package com.example.vertification.service;

import com.example.vertification.entity.User;
import com.example.vertification.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.vertification.Utils.RedisUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

@Service
public class UserService {

    @Autowired
    private RedisUtil redisUtil;

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User createUser(User user) {
        return userRepository.save(user);
    }

    public User Login(String account,String password) {
        User u1 = userRepository.findByTelephoneAndPassword(account,password);
        User u2 =  userRepository.findByNameAndPassword(account,password);
        if(u1 != null){
            redisUtil.setToken(UUID.randomUUID().toString(),u1.getUid().toString());
            return u1;
        }else if( u2!=null){
            redisUtil.setToken(UUID.randomUUID().toString(),u2.getUid().toString());
            return u2;
        }else{
            return null;
        }
    }


    public String encryptPassword(String plainPassword) {
        try {
            // 使用与存储时相同的密钥和算法加密密码
            String key = "zjprovince123456"; // 注意：这只是一个示例密钥，实际使用中应该更安全
            Cipher cipher = Cipher.getInstance("AES");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptedPasswordBytes = cipher.doFinal(plainPassword.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedPasswordBytes); // 使用Base64编码加密后的字节数组
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Password encryption failed", e);
        }
    }

    public User getUserByAccountAndPassword(String account,String password) {
        User u1 = userRepository.findByTelephoneAndPassword(account,password);
        User u2 =  userRepository.findByNameAndPassword(account,password);
        if(u1 != null){
            return u1;
        }else if( u2!=null){
            return u2;
        }else{
            return null;
        }
    }


    public String getTokenByAccountAndPassword(String account,String password) {
        User u1 = userRepository.findByTelephoneAndPassword(account,password);
        User u2= userRepository.findByNameAndPassword(account,password);
        if(u1!=null){
            return redisUtil.getTokenByUID(String.valueOf(u1.getUid()));
        }
        if(u2!=null) {
            return redisUtil.getTokenByUID(String.valueOf(u2.getUid()));
        }else{
            return null;
        }
    }



    public String getTokenByUID(String uid){
        return redisUtil.getTokenByUID(uid);
    }

    public String getUidByToken(String uuid){
        return redisUtil.getUIDByToken(uuid);
    }

    public User getUserByToken(String uuid){
        if(uuid==null){
            return null;
        }
        String uidString = redisUtil.getUIDByToken(uuid);
        if (uidString != null) {
            Long uid = Long.parseLong(uidString);
            return userRepository.findByUid(uid);
        } else {
            // 处理 uid 为 null 的情况，例如返回 null 或者抛出异常
            // 这里可以根据业务需求进行自定义处理
            return null; // 或者你可以抛出更具体的异常，例如 UserNotFoundException
        }
    }





    // 保存用户
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    // 更新用户（需要先通过ID或其他方式获取到实体，然后修改其属性，最后保存）
    public User updateUser(User user) {
        return userRepository.save(user);
    }


    // 根据ID删除用户
    public void deleteUser(Long uid) {
        userRepository.deleteById(uid);
    }

    // 根据ID获取用户
    public User getUserByUId(Long uid) {
        return userRepository.findById(uid).orElse(null);
    }



    // 根据电话号码获取用户
    public User getUserByTelephone(String telephone) {
        return userRepository.findByTelephone(telephone);
    }

    // 获取所有管理员用户
    public List<User> getAll() {
        // 假设管理员的position值为2
        return userRepository.findAll();
    }

    // 其他业务逻辑方法...
}